package com.project.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.project.bean.UserBean;
import com.project.mapper.IGradeMapper;
import com.project.mapper.IRoleMapper;
import com.project.mapper.IUserMapper;
import com.project.service.IUserService;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@Transactional
public class UserServiceImpl implements IUserService {

    @Autowired
    private IUserMapper userMapper;
    @Autowired
    private IRoleMapper roleMapper;
    @Autowired
    private IGradeMapper gradeMapper;

    @Override
    public UserBean findByName(String userName) {
        QueryWrapper<UserBean> qw = new QueryWrapper<>();
        qw.eq("u_name", userName);
        UserBean user = userMapper.selectOne(qw);
        user.setRoleList(roleMapper.findByUser(user.getId()));
        user.setGradeList(gradeMapper.findByUser(user.getId()));
        return user;
    }

    @Override
    public void add(UserBean userBean) {
        userBean.setSalt(this.getSalt());
        Md5Hash md5Hash = new Md5Hash(userBean.getPwd(), userBean.getSalt(), 1024);
        userBean.setPwd(md5Hash.toHex());
        userMapper.insert(userBean);

    }

    private String getSalt() {
        String str = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!@#$%^&*()";
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < 6; i++) {
            int index = (int) (Math.random() * str.length());
            sb.append(str.charAt(index));
        }
        return sb.toString();
    }

}
